package com.byx.chatclient.view.fragment.user;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.byx.chatclient.R;
import com.byx.chatclient.entity.RegisterWay;
import com.byx.chatclient.entity.Result;
import com.byx.chatclient.entity.ResultCallback;
import com.byx.chatclient.factory.RetrofitFactory;
import com.byx.chatclient.http.ApiUrl;
import com.byx.chatclient.utils.ValidateUtil;
import com.byx.chatclient.view.activity.user.RegisterActivity;
import com.byx.chatclient.view.fragment.BaseFragment;
import com.google.gson.JsonElement;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import soup.neumorphism.NeumorphButton;

/**
 * RegisterOneFragment
 * 注册页1，通过邮箱获取验证码并验证
 * @author Superb
 * @date 2021/4/14 16:30
 */
public class RegisterOneFragment extends Fragment {
    @BindView(R.id.et_number)
    protected EditText mEtNumber;
    @BindView(R.id.et_verification)
    protected EditText mEtVerification;
    @BindView(R.id.btn_verification)
    protected NeumorphButton mBtnVerification;
    @BindView(R.id.btn_reg_one_submit)
    protected NeumorphButton mBtnRegOne;

    private Unbinder unbinder;


    /**
     * Called to have the fragment instantiate its user interface view.
     * This is optional, and non-graphical fragments can return null. This will be called between
     * {@link #onCreate(Bundle)} and {@link #onActivityCreated(Bundle)}.
     * <p>A default View can be returned by calling {@link # Fragment(int)} in your
     * constructor. Otherwise, this method returns null.
     *
     * <p>It is recommended to <strong>only</strong> inflate the layout in this method and move
     * logic that operates on the returned View to {@link #onViewCreated(View, Bundle)}.
     *
     * <p>If you return a View from here, you will later be called in
     * {@link #onDestroyView} when the view is being released.
     *
     * @param inflater           The LayoutInflater object that can be used to inflate
     *                           any views in the fragment,
     * @param container          If non-null, this is the parent view that the fragment's
     *                           UI should be attached to.  The fragment should not add the view itself,
     *                           but this can be used to generate the LayoutParams of the view.
     * @param savedInstanceState If non-null, this fragment is being re-constructed
     *                           from a previous saved state as given here.
     * @return Return the View for the fragment's UI, or null.
     */
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_register_one, container, false);
        unbinder = ButterKnife.bind(this,root);
        return root;
    }


    /**
     * 点击切换到注册页
     */
    @OnClick({R.id.btn_verification,R.id.btn_reg_one_submit})
    public void onClick(View view) {
        if (view.getId() == R.id.btn_verification){
            String email = mEtNumber.getText().toString().trim();
            if (!ValidateUtil.isEmailValid(email)){
                Toast.makeText(requireContext(),"邮箱不合要求！",Toast.LENGTH_SHORT).show();
            }else {
                RetrofitFactory.getBean(ApiUrl.class).getVerificationCodeForRegister(email, RegisterWay.BY_EMAIL)
                        .enqueue(new ResultCallback<Boolean>() {
                            @Override
                            public void onResultSuccess(Boolean data) {
                                if (data){
                                    sendVerificationCodeSuccess();
                                }
                            }

                            @Override
                            public void onResultFailure(int code, String msg) {

                            }
                        });
            }
        }else {
            String email = mEtNumber.getText().toString().trim();
            String code = mEtVerification.getText().toString().trim();
            if (!ValidateUtil.isEmailValid(email)){
                Toast.makeText(requireContext(),"邮箱不合要求！",Toast.LENGTH_SHORT).show();
            }else if (!ValidateUtil.isVerificationValid(code)){
                Toast.makeText(requireContext(),"验证码不合要求",Toast.LENGTH_SHORT).show();
            }else {
                RetrofitFactory.getBean(ApiUrl.class).checkVerificationCode(email, code)
                        .enqueue(new ResultCallback<Boolean>() {
                            @Override
                            public void onResultSuccess(Boolean data) {
                                if (data){
                                    ((RegisterActivity) requireActivity()).setEmail(email);
                                    ((RegisterActivity) requireActivity()).registerStepIn();
                                }else {
                                    Toast.makeText(getContext(),"验证码错误！",Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onResultFailure(int code, String msg) {

                            }
                        });
            }
        }
    }

    /**
     * 发送验证码成功
     */
    public void sendVerificationCodeSuccess() {
        new CountDownTimer(60*1000,1000){

            /**
             * Callback fired on regular interval.
             *
             * @param millisUntilFinished The amount of time until finished.
             */
            @Override
            public void onTick(long millisUntilFinished) {
                if (mBtnVerification != null) {
                    mBtnVerification.setEnabled(false);
                    mBtnVerification.setText("已发送（"+millisUntilFinished/1000+"s)");
                }
            }

            /**
             * Callback fired when the time is up.
             */
            @Override
            public void onFinish() {
                if (mBtnVerification != null) {
                    mBtnVerification.setEnabled(true);
                    mBtnVerification.setText("重新发送");
                }
            }
        }.start();
    }

    /**
     * Called when the view previously created by {@link #onCreateView} has
     * been detached from the fragment.  The next time the fragment needs
     * to be displayed, a new view will be created.  This is called
     * after {@link #onStop()} and before {@link #onDestroy()}.  It is called
     * <em>regardless</em> of whether {@link #onCreateView} returned a
     * non-null view.  Internally it is called after the view's state has
     * been saved but before it has been removed from its parent.
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
